package com.imooc.miaosha.config;

import com.alibaba.fastjson.TypeReference;
import com.imooc.miaosha.Message.MiaoshaMessage;
import com.imooc.miaosha.Message.OrderStatusMessage;
import com.imooc.miaosha.common.Const;
import com.imooc.miaosha.service.OrderService;
import com.imooc.miaosha.service.PayService;
import com.imooc.miaosha.service.SecondKillService;
import com.imooc.miaosha.util.JsonUtil;
import com.rabbitmq.client.AMQP;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class RabbitListen {
    @Autowired
    SecondKillService secondKillService;
    @Autowired
    PayService payService;

    @RabbitListener(queues = RabbitMqConfig.ORDER_QUEUE)
    public void listen(String orderJson) {
        MiaoshaMessage miaoshaMessage = JsonUtil.String2Obj(orderJson, new TypeReference<MiaoshaMessage>() {
        });
        log.info("===收到消息==={}==", miaoshaMessage);
        secondKillService.receiveOrder(miaoshaMessage.getUser(), miaoshaMessage.getMiaoshaId(), miaoshaMessage.getShippingId());
    }

    @RabbitListener(queues = RabbitMqConfig.ORDER_STATUS_QUEUE_NAME)
    public void orderStatusListener(String orderStatusJson) {
        OrderStatusMessage orderStatusMessage=JsonUtil.String2Obj(orderStatusJson,new TypeReference<OrderStatusMessage>(){});
        payService.updateOrderStatus(orderStatusMessage.getOrderId(),orderStatusMessage.getUserId(),Const.ORDER_STATUS.PAYED);
        log.info("===收到消息==={}==",orderStatusMessage.toString());
    }
}
